package cn.wj.school.app.net.client.handler;

import cn.wj.school.app.enums.SessionFactory;
import cn.wj.school.common.dto.BaseMsg;
import cn.wj.school.common.manager.ManagerBuilder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: yueding
 * @Description: 客户端处理器
 * @Date: Created in 19:42 2018/12/27
 * @Modified By: yueding Copyright(c) cai-inc.com
 */

@ChannelHandler.Sharable
public class ClientChannelHandler extends SimpleChannelInboundHandler<BaseMsg> {

    private CountDownLatch lathc;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("激活时间是：" + new Date());
        System.out.println("HeartBeatClientHandler channelActive");
        // 注册session
        SessionFactory.INSTANCE.registerSession(ctx.channel());
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionFactory.INSTANCE.removeSession();
        System.out.println("停止时间是：" + new Date());
        System.out.println("HeartBeatClientHandler channelInactive");
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseMsg msg) throws Exception {
        ManagerBuilder.getManagerBuilder().exec(msg, ctx.channel());
        ReferenceCountUtil.release(msg);
    }

    public void resetLatch(CountDownLatch lathc) {
        this.lathc = lathc;
    }
}
